package goodroommate.service.impl;

import java.util.ArrayList;

import goodroommate.dal.DatabaseSession;
import goodroommate.dao.IMessageDao;
import goodroommate.dao.impl.MessageDao;
import goodroommate.domain.Message;
import goodroommate.exception.DatabaseException;
import goodroommate.exception.ItemNotExistsException;
import goodroommate.service.IMessageService;

public class MessageService implements IMessageService {

	IMessageDao messageDao=new MessageDao();
	@Override
	public boolean addMessage(long source, long destination, int handle) throws DatabaseException {
		
		if(source==0)
			return false;
		if(destination==0)
			return false;
		if(handle==1)
			return false;
		try(DatabaseSession dbs=new DatabaseSession()){
			Message message=new Message();
			message.setSource(source);
			message.setDestination(destination);
			message.setHandle(handle);
			return messageDao.addMessage(message, dbs);	
		}
	}

	@Override
	public boolean updateMessageHandle(long messageid) throws DatabaseException {
		
		if(messageid==0)
			return false;
		
		try(DatabaseSession dbs=new DatabaseSession()){
			Message message=messageDao.getMessageById(messageid, dbs);
			return messageDao.updateMessageHandle(message, dbs);
		}
	}

	@Override
	public ArrayList<Message> getMessages(long source, long destination, int handle)
			throws DatabaseException, ItemNotExistsException {
		try(DatabaseSession dbs=new DatabaseSession()){
			ArrayList<Message> rst = messageDao.getMessages(source, destination, handle, dbs);
			if(rst.size()==0)
				throw new ItemNotExistsException();
			return rst;
		}
	}

}
